package com.usb.serial.device;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Vector;

import static com.usb.serial.device.SerialUtils.ByteArrToHex;


public class UsbSerialActivity extends Activity implements View.OnClickListener {
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usb_serial_device);
        initView();

        initSerial();

        initSerialBaudrates();

        initSerialHelper();

    }
    ArrayAdapter uartbaudreatesAdapter;

    private void initSerialBaudrates() {
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.baudrates_value,android.R.layout.simple_spinner_item);
//        String[] stringArray = getResources().getStringArray(R.array.baudrates_value);
   //     uartbaudreatesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stringArray);
        String[] stringArray = getResources().getStringArray(R.array.baudrates_value);
        uartbaudreatesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stringArray);
        uartbaudreatesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_baudrate_coma.setAdapter(uartbaudreatesAdapter);
        spinner_baudrate_coma.setSelection(14);
        spinner_baudrate_coma.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //   Log.i(TAG, "onItemSelected: "+view +" position:"+position+" id:"+id);
                int selectedItemPosition = spinner_baudrate_coma.getSelectedItemPosition();
                Log.i(TAG, "selectedItemPosition: " + selectedItemPosition);
                String itemAtPosition = (String) spinner_baudrate_coma.getItemAtPosition(position).toString();
                Log.i(TAG, "itemAtPosition: " + itemAtPosition);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.i(TAG, "onNothingSelected: ");
            }
        });

    }

    ArrayAdapter uartlistAdapter;
    Vector<String> mSerialDeviceName;

    private void initSerial() {

        Vector<File> devices = getDevices();
        uartlistAdapter = new ArrayAdapter<File>(this, android.R.layout.simple_spinner_item, devices);
        uartlistAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        serial_spinner_coma.setAdapter(uartlistAdapter);
        serial_spinner_coma.setSelection(1);
        serial_spinner_coma.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //   Log.i(TAG, "onItemSelected: "+view +" position:"+position+" id:"+id);
                int selectedItemPosition = serial_spinner_coma.getSelectedItemPosition();
                Log.i(TAG, "selectedItemPosition: " + selectedItemPosition);
                String itemAtPosition = (String) serial_spinner_coma.getItemAtPosition(position).toString();
                Log.i(TAG, "itemAtPosition: " + itemAtPosition);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.i(TAG, "onNothingSelected: ");
            }
        });


    }

    Vector<File> mDevices = null;

    public Vector<File> getDevices() {
        if (mDevices == null) {
            mDevices = new Vector<File>();
            File dev = new File("/dev");
            File[] files = dev.listFiles();
            Log.i(TAG, "getDevices: " + files.length);
            int i;
            for (i = 0; i < files.length; i++) {
                //   Log.i(TAG, "getAbsolutePath: "+files[i].getAbsolutePath());
                if (files[i].getAbsolutePath().contains("tty")) {
                    Log.d(TAG, "Found new device: " + files[i]);
                    mDevices.add(files[i]);
                }
            }
        }
        return mDevices;
    }

    void getDrivers() throws IOException {
        //    mDrivers = new Vector<Driver>();
        LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
        String l;
        while ((l = r.readLine()) != null) {
            // Issue 3:
            // Since driver name may contain spaces, we do not extract driver name with split()
            String drivername = l.substring(0, 0x15).trim();
            Log.i(TAG, "drivername: " + drivername);
            String[] w = l.split(" +");
            if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
                Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length - 4]);
                //      mDrivers.add(new Driver(drivername, w[w.length-4]));
            }
        }
        r.close();
    }

    SerialControl serialControl;

    public void initSerialHelper() {
        serialControl = new SerialControl();
    }

    class SerialControl extends SerialHelper {

        @Override
        protected void onDataReceived(final ComBean comBean) {

            runOnUiThread(new Runnable()
            {
                public void run()
                {
                    Log.i(TAG, "DispRecData: ");
                    DispRecData(comBean);
                }
            });

        }

    }



    StringBuilder sMsg;
    private void DispRecData(SerialHelper.ComBean ComRecData){
        if (sMsg == null) {
             sMsg = new StringBuilder();
        }
        byte[] bytes = ComRecData.bytes;
        String byteArrToHex ="";
        if (txtorandhexshow.isChecked()){
            //16进制
            byteArrToHex = ByteArrToHex(ComRecData.bytes);
        }else {
            //10进制
            byteArrToHex =   new String(bytes);
        }
    //    String byteArrToHex = ByteArrToHex(ComRecData.bytes);
        Log.i(TAG, "byteArrToHex: "+byteArrToHex);
        sMsg.append(ComRecData.sRecTime);
        sMsg.append("[");
        sMsg.append(" ");
        sMsg.append(ComRecData.sPort);
        sMsg.append("]");
        sMsg.append(byteArrToHex);
        sMsg.append("\r\n");
        usb_serial_read_edit.setText(sMsg);
    }

    String TAG = UsbSerialActivity.class.getSimpleName();
    EditText usb_serial_read_edit;
    EditText edit_serial_coma;
    Spinner serial_spinner_coma;
    Spinner spinner_baudrate_coma;
    ToggleButton serial_toggle_coma;
    EditText edit_serial_time_coma;
    TextView text_serial_name;
    CheckBox serial_checkbox_auto_coma;
    Button serial_btn_send_coma;

    CheckBox txtorandhexshow;

    private void initView() {
        usb_serial_read_edit = findViewById(R.id.usb_serial_read_edit);
        edit_serial_coma = findViewById(R.id.edit_serial_coma);
        serial_spinner_coma = findViewById(R.id.serial_spinner_coma);
        spinner_baudrate_coma = findViewById(R.id.spinner_baudrate_coma);

        txtorandhexshow =   findViewById(R.id.txtorandhexshow);
        txtorandhexshow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
                Log.i(TAG, "onCheckedChanged: "+ischecked);
                if (ischecked) {
                    txtorandhexshow.setText("十六进制");
                }else{
                    txtorandhexshow.setText("十进制");
                }
            }
        });
        if (txtorandhexshow.isChecked()) {
            txtorandhexshow.setChecked(true);
            txtorandhexshow.setText("十六进制");
        }else{
            txtorandhexshow.setChecked(false);
            txtorandhexshow.setText("十进制");
        }


        serial_toggle_coma = findViewById(R.id.serial_toggle_coma);
        serial_toggle_coma.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG, "onCheckedChanged: " + isChecked);
                if (isChecked) {
                    try {
                        serialControl.setPort(serial_spinner_coma.getSelectedItem().toString());
                        serialControl.setBaudRate(spinner_baudrate_coma.getSelectedItem().toString());
                        File file =new File(serial_spinner_coma.getSelectedItem().toString());
                        boolean b = file.canRead();
                        boolean b1 = file.canWrite();
                        Log.i(TAG, "onCheckedChanged: "+b +" b1:"+b1);

                        Log.i(TAG, "Os.chmod: "+serial_spinner_coma.getSelectedItem().toString());
                        try {
                        //    Os.chmod(serial_spinner_coma.getSelectedItem().toString(), 0666);

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if (!file.canRead() || !file.canWrite()) {
                            Toast.makeText(UsbSerialActivity.this,serial_spinner_coma.getSelectedItem().toString()+"：：无权限",Toast.LENGTH_SHORT).show();
                            serial_toggle_coma.setChecked(false);
                            return;
                        }
                        serialControl.open();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    serialControl.close();
                    serial_toggle_coma.setChecked(false);
                }
            }
        });

        serial_btn_send_coma = findViewById(R.id.serial_btn_send_coma);
        serial_btn_send_coma.setOnClickListener(new ButtonClickEvent());

        Button clear_btn_send_coma = findViewById(R.id.clear_btn_send_coma);
        clear_btn_send_coma.setOnClickListener(new ClearButtonClickEvent());
    }
    class ClearButtonClickEvent implements View.OnClickListener {
        public void onClick(View v)
        {
            if (sMsg !=null){
            sMsg.delete(0, sMsg.length());
            usb_serial_read_edit.setText("");
        }

        }
    }
    public static String stringToHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }


    class ButtonClickEvent implements View.OnClickListener {
        public void onClick(View v)
        {
            String editComa = edit_serial_coma.getText().toString().trim();
            Log.i(TAG, "editComa: "+editComa);
            String string2 = hexStringToString(editComa);

            sendPortData(serialControl, string2);
            String serialSendData = getResources().getString(R.string.app_serial_send_data);
            Toast.makeText(getApplicationContext(),serialSendData+edit_serial_coma.getText().toString(),Toast.LENGTH_SHORT).show();

        }
    }
    private void sendPortData(SerialHelper ComPort, String sOut){
        if (ComPort!=null && ComPort.isOpen())
        {
            Log.i(TAG, "sendPortData: "+sOut);
                ComPort.sendTxt(sOut);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }
}
